package zy.service.sys.kpi.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import zy.dao.sys.kpi.KpiDAO;
import zy.entity.sys.kpi.T_Sys_Kpi;
import zy.entity.sys.kpi.T_Sys_KpiScore;
import zy.service.sys.kpi.KpiService;
import zy.util.StringUtil;

@Service
public class KpiServiceImpl implements KpiService{
	@Resource
	private KpiDAO kpiDAO;
	
	@Override
	public List<T_Sys_Kpi> list(Map<String, Object> params) {
		return kpiDAO.list(params);
	}
	
	@Override
	public List<T_Sys_KpiScore> listScores(Map<String, Object> params) {
		return kpiDAO.listScores(params);
	}
	
	@Override
	@Transactional
	public void save(T_Sys_Kpi kpi,List<T_Sys_KpiScore> kpiScores) {
		if(StringUtil.isEmpty(kpi.getKi_code())){
			throw new IllegalArgumentException("指标编号不能为空");
		}
		if (kpiScores == null || kpiScores.size() == 0) {
			throw new IllegalArgumentException("请设置区间范围");
		}
		
		T_Sys_Kpi existKpi = kpiDAO.check(kpi.getKi_code(), kpi.getKi_shop_code(), kpi.getCompanyid());
		if(existKpi != null){
			throw new RuntimeException("该指标已经存在，请返回直接设置区间范围");
		}
		for (T_Sys_KpiScore item : kpiScores) {
			item.setKs_ki_code(kpi.getKi_code());
			item.setKs_shop_code(kpi.getKi_shop_code());
			item.setCompanyid(kpi.getCompanyid());
		}
		kpiDAO.save(kpi, kpiScores);
	}
	
	@Override
	@Transactional
	public void update(T_Sys_Kpi kpi,List<T_Sys_KpiScore> kpiScores) {
		if(StringUtil.isEmpty(kpi.getKi_code())){
			throw new IllegalArgumentException("指标编号不能为空");
		}
		if (kpiScores == null || kpiScores.size() == 0) {
			throw new IllegalArgumentException("请设置区间范围");
		}
		kpiDAO.deleteScores(kpi.getKi_code(), kpi.getKi_shop_code(), kpi.getCompanyid());
		for (T_Sys_KpiScore item : kpiScores) {
			item.setKs_ki_code(kpi.getKi_code());
			item.setKs_shop_code(kpi.getKi_shop_code());
			item.setCompanyid(kpi.getCompanyid());
		}
		kpiDAO.saveScores(kpiScores);
	}
	
	@Override
	@Transactional
	public void del(String ki_code,String shop_code,Integer companyid) {
		//TODO 验证是否存在业务关联关系
		kpiDAO.delete(ki_code, shop_code, companyid);
		kpiDAO.deleteScores(ki_code, shop_code, companyid);
	}
	
}
